<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useMerchantStore } from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";

const merchantStore = useMerchantStore();
const orders = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 订单详情
const orderDetail = ref<any>(null);
const detailDialogVisible = ref(false);
const detailLoading = ref(false);

// 获取状态中文标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    ORDER_CREATED: "已创建",
    PENDING: "支付成功",
    MERCHANT_CONFIRMED: "商家已确认",
    COOKING: "备餐中",
    READY_WAITING_RIDER: "等待骑手",
    RIDER_ASSIGNED: "骑手已分配",
    FOOD_PICKED: "骑手已取餐",
    DELIVERING: "配送中",
    DELIVERED: "已送达",
    COMPLETED: "已完成",
    CANCELLED: "已取消",
  };
  return statusMap[status] || status;
};

// 获取状态类型
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    ORDER_CREATED: "info",
    PENDING: "warning",
    MERCHANT_CONFIRMED: "success",
    COOKING: "warning",
    READY_WAITING_RIDER: "warning",
    RIDER_ASSIGNED: "primary",
    FOOD_PICKED: "primary",
    DELIVERING: "primary",
    DELIVERED: "success",
    COMPLETED: "success",
    CANCELLED: "danger",
  };
  return typeMap[status] || "info";
};

// 格式化状态标签，每两个字一行
const formatStatusLabel = (status: string): string => {
  const label = getStatusLabel(status);
  if (label.length <= 2) return label;

  // 对于长度大于2的标签，每两个字一行
  const chars = label.split("");
  let result = "";
  for (let i = 0; i < chars.length; i += 2) {
    result += chars[i];
    if (i + 1 < chars.length) {
      result += chars[i + 1];
    }
    if (i + 2 < chars.length) {
      result += "\n";
    }
  }
  return result;
};

// 获取订单列表
const fetchOrders = async () => {
  if (!merchantStore.currentStoreId) {
    orders.value = [];
    return;
  }

  loading.value = true;
  try {
    const { getOrders } = await import("@/api/index");
    const ordersRes = await getOrders(merchantStore.currentStoreId, {
      page: currentPage.value,
      size: pageSize.value,
    });

    console.log("订单数据返回:", ordersRes);

    // 处理返回数据
    const data = ordersRes.data?.data || ordersRes.data;
    if (data) {
      // 如果是分页数据 (新的API格式)
      if (data.content && typeof data.totalElements === "number") {
        orders.value = data.content;
        total.value = data.totalElements;
      }
      // 如果是旧的分页格式
      else if (data.list && typeof data.total === "number") {
        orders.value = data.list;
        total.value = data.total;
      }
      // 如果直接返回数组
      else if (Array.isArray(data)) {
        orders.value = data;
        total.value = data.length;
      } else {
        orders.value = [];
        total.value = 0;
      }
    } else {
      orders.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取订单列表失败", error);
    ElMessage.error("获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 查看订单详情
const viewOrderDetail = async (orderId: string) => {
  detailDialogVisible.value = true;
  detailLoading.value = true;

  try {
    const { getDetailOrders } = await import("@/api/index");

    // 从订单列表中找到当前订单，获取userId
    const currentOrder = orders.value.find((order) => order.id === orderId);
    const userId = currentOrder?.userId || "";

    console.log(
      `获取订单详情，storeId: ${merchantStore.currentStoreId}, userId: ${userId}, orderId: ${orderId}`
    );
    const res = await getDetailOrders(
      merchantStore.currentStoreId,
      orderId
    );
    console.log("订单详情返回:", res);
    orderDetail.value = res.data?.data || res.data;
  } catch (error) {
    console.error("获取订单详情失败", error);
    ElMessage.error("获取订单详情失败");
    detailDialogVisible.value = false; // 关闭对话框，避免显示空白
  } finally {
    detailLoading.value = false;
  }
};

// 更新订单状态
const updateOrderStatus = async (orderId: string, status: string) => {
  try {
    await ElMessageBox.confirm(
      `确定将订单状态更新为"${getStatusLabel(status)}"吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const { updateOrderStatus } = await import("@/api/index");
    // 根据API文档格式更新请求参数
    await updateOrderStatus(merchantStore.currentStoreId, orderId, {
      orderStatus: status,
    });
    ElMessage.success("订单状态已更新");

    // 刷新订单列表
    fetchOrders();

    // 如果订单详情对话框打开，也更新详情
    if (detailDialogVisible.value && orderDetail.value?.id === orderId) {
      orderDetail.value.status = status;
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("更新订单状态失败", error);
      ElMessage.error("更新订单状态失败");
    }
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchOrders();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchOrders();
};

onMounted(async () => {
  // 确保店铺信息已加载
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores();
  }

  // 获取订单列表
  await fetchOrders();
});

// 监听店铺变化
watch(
  () => merchantStore.currentStoreId,
  () => {
    currentPage.value = 1;
    fetchOrders();
  }
);
</script>

<template>
  <merchant-layout>
    <div class="orders-view">
      <el-card class="orders-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>订单管理</span>
          </div>
        </template>

        <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
          <el-empty description="请先选择店铺" />
        </div>

        <template v-else>
          <el-table
            :data="orders"
            v-loading="loading"
            style="width: 100%"
            stripe
          >
            <el-table-column prop="orderNo" label="订单号" width="180" />
            <el-table-column label="下单时间" width="180">
              <template #default="scope">{{ scope.row.createdAt }}</template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              class-name="status-column"
            >
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ formatStatusLabel(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="商品金额">
              <template #default="scope">¥{{ scope.row.totalAmount }}</template>
            </el-table-column>
            <el-table-column label="配送费">
              <template #default="scope">¥{{ scope.row.deliveryFee }}</template>
            </el-table-column>
            <el-table-column label="优惠金额">
              <template #default="scope"
                >¥{{ scope.row.discountAmount }}</template
              >
            </el-table-column>
            <el-table-column label="实付金额">
              <template #default="scope"
                >¥{{ scope.row.paymentAmount }}</template
              >
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="viewOrderDetail(scope.row.id)"
                  >查看</el-button
                >
                <el-dropdown
                  trigger="click"
                  @command="(cmd) => updateOrderStatus(scope.row.id, cmd)"
                >
                  <el-button size="small" type="primary">
                    更新状态
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="MERCHANT_CONFIRMED"
                        >确认接单</el-dropdown-item
                      >
                      <el-dropdown-item command="COOKING"
                        >备餐中</el-dropdown-item
                      >
                      <el-dropdown-item command="READY_WAITING_RIDER"
                        >等待骑手</el-dropdown-item
                      >
                      <el-dropdown-item command="CANCELLED" divided
                        >取消订单</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </template>
      </el-card>

      <!-- 订单详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="订单详情"
        width="800px"
        destroy-on-close
      >
        <div v-loading="detailLoading">
          <template v-if="orderDetail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单编号">{{
                orderDetail.orderNo
              }}</el-descriptions-item>
              <el-descriptions-item label="下单时间">{{
                orderDetail.createdAt
              }}</el-descriptions-item>
              <el-descriptions-item label="用户id">{{
                orderDetail.deliveryAddress.receiver
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                orderDetail.deliveryAddress.phone
              }}</el-descriptions-item>
              <el-descriptions-item label="配送地址" :span="2">{{
                orderDetail.deliveryAddress.detailAddress
              }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :type="getStatusType(orderDetail.status)">
                  {{ orderDetail.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="支付方式">{{
                orderDetail.paymentType
              }}</el-descriptions-item>
            </el-descriptions>

            <h4 class="detail-title">商品信息</h4>
            <el-table
              :data="orderDetail.items || []"
              border
              style="width: 100%"
            >
              <el-table-column prop="foodName" label="商品名称" />
              <el-table-column prop="price" label="单价">
                <template #default="scope">¥{{ scope.row.price }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column label="小计">
                <template #default="scope"
                  >¥{{
                    (scope.row.price * scope.row.quantity).toFixed(2)
                  }}</template
                >
              </el-table-column>
            </el-table>

            <div class="order-summary">
              <div class="summary-item">
                <span>商品总额：</span>
                <span
                  >¥{{
                    orderDetail.totalAmount || orderDetail.subtotal || 0
                  }}</span
                >
              </div>
              <div class="summary-item">
                <span>配送费：</span>
                <span>¥{{ orderDetail.deliveryFee || 0 }}</span>
              </div>
              <div class="summary-item">
                <span>优惠金额：</span>
                <span
                  >-¥{{
                    orderDetail.discountAmount || orderDetail.discount || 0
                  }}</span
                >
              </div>
              <div class="summary-item total">
                <span>订单总额：</span>
                <span
                  >¥{{
                    orderDetail.paymentAmount || orderDetail.amount || 0
                  }}</span
                >
              </div>
            </div>

            <div
              class="remark"
              v-if="orderDetail.remark || orderDetail.remarks"
            >
              <h4>备注</h4>
              <p>{{ orderDetail.remark || orderDetail.remarks }}</p>
            </div>
          </template>
        </div>
        <template #footer>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-dropdown
            trigger="click"
            @command="(cmd) => updateOrderStatus(orderDetail.id, cmd)"
          >
            <el-button type="primary">
              更新状态
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="MERCHANT_CONFIRMED"
                  >确认接单</el-dropdown-item
                >
                <el-dropdown-item command="COOKING">备餐中</el-dropdown-item>
                <el-dropdown-item command="READY_WAITING_RIDER"
                  >等待骑手</el-dropdown-item
                >
                <el-dropdown-item command="CANCELLED" divided
                  >取消订单</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-dialog>
    </div>
  </merchant-layout>
</template>

<style scoped>
.orders-view {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.store-selector {
  display: flex;
  align-items: center;
}

.store-selector .label {
  margin-right: 10px;
  color: #909399;
}

.el-main {
  padding: 20px;
}

.orders-card {
  border-radius: 18px;
  background: #fffbe7;
  box-shadow: 0 2px 8px #ffd54f33;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-store-tip {
  padding: 30px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.order-summary {
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #606266;
}

.summary-item.total {
  margin-top: 10px;
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.remark {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.remark h4 {
  margin: 0 0 10px;
  font-size: 14px;
  font-weight: 500;
}

.remark p {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

/* 状态标签样式 */
:deep(.el-tag) {
  display: inline-block;
  padding: 6px 10px;
  height: auto;
  min-height: 28px;
  line-height: 1.2;
  font-size: 13px;
  text-align: center;
  white-space: pre-line;
  overflow: visible;
  text-overflow: unset;
}

/* 表格中的状态列宽度 */
.el-table :deep(.el-table__cell.status-column) {
  min-width: 80px;
}

/* 订单详情对话框中的状态标签 */
.el-descriptions :deep(.el-tag) {
  min-width: 80px;
}
</style>
